<template>
  <div>
    <el-row>
      <el-col :span="12" :offset="6">
        <el-form
          label-width="120px"
          ref="ruleFormRef"
          :model="info"
          :rules="rules"
          >
          <el-form-item label="title">
          <el-input v-model="info.title" />
          </el-form-item>
          <el-form-item label="body">
            <el-input
              v-model="info.body"
              :rows="2"
              type="textarea"
              placeholder="Please input"
            />
          </el-form-item>
          <el-form-item>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import {
  reactive,
  toRefs,
  ref,
  onMounted
} from "vue";
import { useRoute, useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
 import { MainInterface } from "@/interface"
import { getMainPostDetial, putMainPostDetial } from "@/store/main";


export default {
 setup() {
   const route = useRoute()
   const router = useRouter()

   const ruleFormRef = ref<FormInstance>()

   const state = reactive({
     info: {} as MainInterface.PostItem,
     id: route.params.id as string ?? ''
   })
   
  const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error('Please input the password'))
    } else {
      callback()
    }
  }

   const rules = reactive({
    title: [{ validator: validatePass, trigger: 'blur' }],
    body: [{ validator: validatePass, trigger: 'blur' }],
   })

   const getData = () => getMainPostDetial({
      option: {
        userId: state.id
      },
      success:(res: MainInterface.PostItem) => {
         state.info = res
      }
    })

  const onSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return

    formEl.validate((valid: boolean) => {
      if (valid) {
        putMainPostDetial({
          option: state.info,
          success: () => {
             ElMessage({
               type: "success",
               message: "更新成功",
               onClose: () => {
                 router.replace({
                  path: '/'
                })
               }
             })
          }
        })
      } else {
        console.log('error submit!')
        return false
      }
    })
  }

  onMounted(() => {
    getData()
  })

  return {
    ...toRefs(state),
    rules,
    ruleFormRef,
    onSubmit
  }
 }
}
</script>